<template>
  <div class="search-wrapper">
    <div class="search-header">
      <van-icon
        class="arrow-left"
        name="arrow-left"
        @click="$router.goBack()"
      />
      <van-search
        class="search-content"
        v-model="value"
        show-action
        :placeholder="place"
        @search="onSearch"
        @input="input"
        @focus="focus"
      >
        <template #action v-if="isExist">
          <div @touchend="onSearch(value)">搜索</div>
        </template>
        <template #action v-else>
          <van-icon
            name="shopping-cart-o"
            :badge="badge"
            id="shop-car"
            class="shop-car"
          />
        </template>
      </van-search>
    </div>
    <div class="like-search" v-if="likeList.length > 0 && isExist">
      <van-cell v-for="item in likeList" :key="item" @click="onSearch(item)">
        <template>
          <!-- 用v-html格式化我们的值，得到我们想要的结果 -->
          <span class="custom-title" v-html="formatHTML(item)"></span>
        </template>
      </van-cell>
    </div>
    <div class="goodsList" v-if="!isExist">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
        :immediate-check="false"
      >
        <GoodsCard
          v-for="(item, i) in goodsList"
          :key="i"
          v-bind="item"
          :num="counterMap[item.id]"
        />
      </van-list>
    </div>
    <!-- 历史记录 -->
    <div class="history-list" v-if="likeList.length <= 0 && isExist">
      <MyHistory :hisList="hisList" @search="onSearch" />
    </div>
  </div>
</template>

<script>
import search from '@/api/search';
import likeSearch from '@/api/likeSearch';
import MyHistory from '@/components/MyHistory.vue';
import { mapState } from 'vuex';
import GoodsCard from '../components/GoodsCard.vue';

export default {
  components: {
    GoodsCard,
    MyHistory,
  },
  data() {
    return {
      place: '酒',
      value: this.place,
      likeList: [], // 模糊搜索结果列表
      timer: null,
      page: 1,
      size: 5,
      goodsList: [],
      loading: false,
      finished: false,
      isExist: true,
      total: 0,
      hisList: [], // 存储历史记录
    };
  },
  computed: {
    ...mapState(['counterMap']),
    badge() {
      const count = Object.values(this.counterMap).reduce(
        (pre, next) => pre + next,
        0,
      );
      if (count > 99) {
        return '99+';
      }
      return count;
    },
  },

  methods: {
    onLoad() {
      search(this.value, this.page, this.size).then((r) => {
        this.goodsList = [...this.goodsList, ...r.list];
        this.total = r.total;
        this.loading = false;
        if (this.goodsList.length >= this.total) {
          this.finished = true;
        } else {
          this.page += 1;
        }
      });
    },
    onSearch(value) {
      if (value) {
        this.value = value;
      } else {
        this.value = this.place;
      }

      //   历史记录**********
      const result = this.hisList.find((item) => item.values === this.value); // 判断本地有无这个值
      if (result) {
        // 如果本地存储有这个值，则更新这个值的时间，并按时间降序排序
        result.time = new Date().getTime();
        this.hisList.sort((a, b) => b.time - a.time);
      } else {
        // 若没有则添加，但最长允许10个，超出从最后一位移除
        this.hisList.unshift({ value: this.value, time: new Date().getTime() });
        if (this.hisList.length > 11) {
          this.hisList.pop();
        }
      }
      localStorage.setItem('historyList', JSON.stringify(this.hisList));

      this.likeList = [];
      this.goodsList = [];
      this.finished = false;
      this.loading = false;
      this.page = 1;
      this.onLoad();
      this.loading = true;

      this.isExist = false;
    },
    input() {
      if (this.value === '') {
        this.likeList = [];
        return;
      }
      if (this.timer) {
        clearTimeout(this.timer);
        this.timer = null;
      } else {
        this.timer = setTimeout(async () => {
          const resp = await likeSearch(this.value);
          this.likeList = resp.result;
          clearTimeout(this.timer);
          this.timer = null;
        }, 300);
      }
    },
    focus() {
      this.isExist = true;
    },
    formatHTML(value) {
      const reg = new RegExp(this.value, 'g');
      return value.replace(reg, this.value.fontcolor('red'));
    },
  },
  created() {
    //   要在一开始就获取本地有无历史记录
    this.hisList = JSON.parse(localStorage.getItem('historyList')) || [];
  },
};
</script>

<style lang="less" scoped>
.search-wrapper {
  width: 100%;
  height: 100vh;
  z-index: 10;
  background: #fff;
  .search-header {
    width: 345px;
    background: #fff;
    margin: 0 auto;
    display: flex;
    align-items: center;
    position: fixed;
    top: 0;
    left: 15px;
    z-index: 22;
    .arrow-left {
      font-size: 22px;
    }
    .search-content {
      flex: 1;
      .shop-car {
        font-size: 20px;
      }
    }
  }
  .like-search {
    position: relative;
    top: 50px;
    width: 100%;
    box-sizing: border-box;
    padding-left: 30px;
  }
  .goodsList {
    position: relative;
    width: 345px;
    margin: 48px auto 0;
    z-index: 10;
    background: #fff;
  }
  .history-list {
    width: 350px;
    position: absolute;
    top: 55px;
    left: 10px;
    z-index: 1;
  }
}
</style>
